package com.czp.framework.listener;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
 * 【描 述】：在线统计监听器
 * 【环 境】：J2SE 1.7
 * @author   柴志鹏	CHAIZP@GMAIL.COM
 * @version  version 1.0
 * @since    2014-9-4
 */
public class OnlineListener implements HttpSessionAttributeListener {
	/**
	 * 定义监听的session属性名.
	 */
	public final static String LISTENER_NAME = "userSession";

	/**
	 * 定义存储客户登录session的集合.
	 */
	private static List<Object> sessions = new ArrayList<Object>();

	/**
	 * 加入session时的监听方法.
	 * @param HttpSessionBindingEvent
	 *            session事件
	 */
	public void attributeAdded(HttpSessionBindingEvent sbe) {
		//当用户session不存在时
		if(!sessions.contains(sbe.getValue())) {
			if (LISTENER_NAME.equals(sbe.getName())) {
				sessions.add(sbe.getValue());
			}
		}
	}

	/**
	 * session失效时的监听方法.
	 * @param HttpSessionBindingEvent
	 *            session事件
	 */
	public void attributeRemoved(HttpSessionBindingEvent sbe) {
		if (LISTENER_NAME.equals(sbe.getName())) {
			sessions.remove(sbe.getValue());
		}
	}

	/**
	 * session覆盖时的监听方法.
	 * @param HttpSessionBindingEvent
	 *            session事件
	 */
	public void attributeReplaced(HttpSessionBindingEvent sbe) {
		System.out.println(this.getClass().getName() + "监听器变更触发.");
	}

	/**
	 * 返回客户登录session的集合.
	 * @return
	 */
	public static List<Object> getSessions() {
		return sessions;
	}
	
	/*
	 * http://blog.sina.com.cn/s/blog_705c12080100nayb.html
	 * http://www.blogjava.net/zhaijianhui/archive/2006/07/31/61072.html
	 * http://stephen830.iteye.com/blog/338291
	 * */

}
